package com.example.homework7;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import java.security.MessageDigest;

public class shared extends Fragment {
    public shared(){
        super(R.layout.shared);
    }
    private EditText[] editTexts;
    private final int EditCount = 2;
    private int[] EditID = new int[]{R.id.editTextPhone, R.id.editTextTextPassword};
    private String[] EditValueKey = new String[]{"account", "password"};
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        SharedPreferences sp = getActivity().getPreferences(Context.MODE_PRIVATE);
        editTexts = new EditText[EditCount];
        for (int i = 0; i < EditCount; i++)
            editTexts[i] = getView().findViewById(EditID[i]);
        getView().findViewById(R.id.button5).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences.Editor editor = sp.edit();
                editor.putString(EditValueKey[0], editTexts[0].getText().toString());
                editor.putString(EditValueKey[1],getSHA256(editTexts[1].getText().toString()));
                editor.commit();
                Toast.makeText(getContext(), "保存成功!", Toast.LENGTH_SHORT).show();
            }
        });
        for (int i = 0; i < EditCount; i++)
            editTexts[i].setText(sp.getString(EditValueKey[i], ""));
    }
    private String getSHA256(String str) {
        MessageDigest messageDigest;
        String encodeStr = "";
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(str.getBytes("UTF-8"));
            encodeStr = byteHex((messageDigest.digest()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return encodeStr;
    }
    private String byteHex(byte[] bytes){
        StringBuffer stringBuffer = new StringBuffer();
        String temp = null;
        for (int i = 0; i < bytes.length; i++) {
            temp = Integer.toHexString(bytes[i] & 0xFF);
            if(temp.length() == 1)
                stringBuffer.append("0");
            stringBuffer.append(temp);
        }
        return stringBuffer.toString();
    }
}